'use strict'

const fs = require('fs')
const path = require('path')
const sendToWormhole = require('stream-wormhole')
// 这个是自带的,不用安装
const pump = require('mz-modules/pump')
const Controller = require('egg').Controller
const accessDir = require('../utils/access-dir')

class FilesContronller extends Controller {
  // 单文件上传
  async upload() {
    const { ctx } = this
    const stream = await ctx.getFileStream()
    const fileName = Math.random().toString(32).slice(2) + Date.now() + path.extname(stream.filename).toLowerCase()

    // 这里保存到了'public'文件夹中
    const saveDir = await accessDir(path.resolve(__dirname, '../public/upload'))
    const savePath = path.join(saveDir, fileName)
    const writeStream = fs.createWriteStream(savePath)

    try {
      await pump(stream, writeStream)
    } catch (err) {
      sendToWormhole(stream)
      writeStream.destroy()
      throw err
    }

    ctx.body = {
      code: 2000,
      data: '/public/upload/' + fileName,
      msg: 'ok',
    }
  }

  async download() {
    const { ctx } = this
    const filePath = path.resolve(__dirname, '../public/upload/7vsq482fj81605059023441.png')
    ctx.attachment(filePath)
    ctx.set(('Content-Type', 'application/octet-stream'))
    ctx.body = fs.createReadStream(filePath)
  }
}

module.exports = FilesContronller
